<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="filters">
        <el-form-item>
          <el-input v-model="filters.name" placeholder="关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="departments" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="name" label="部门名称" width="120" >
      </el-table-column>
      <el-table-column prop="sn" label="部门编号" width="100" >
      </el-table-column>
      <el-table-column prop="state" label="状态" width="100" sortable>
        <template scope="scope">
          <span v-if="scope.row.state == 1" style="color: green">启用</span>
          <span v-else-if="scope.row.state == 0" style="color: red">禁用</span>
          <span v-else>未知</span>
        </template>
      </el-table-column>
      <el-table-column prop="manager.username" label="负责人" width="120" >
      </el-table-column>
      <el-table-column prop="parent.name" label="上级部门" min-width="180" >
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" v-perm="'department:deleteById'" @click="handleDel(scope.$index, scope.row)">删除</el-button><!--第一个参数是 行数索引-->
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="pageSize" :current-page="currentPage" :totals="totals" style="float:right;">
      </el-pagination>
    </el-col>

    <!--
     private String sn;
     private String name;
     private Integer state;

     private Employee manager;
     private Department parent
     -->
    <!--编辑界面-->
    <!--rules:绑定表单校验规则-->
    <el-dialog :title="title" :visible.sync="editFormVisible" :close-on-click-modal="false">
      <el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="editForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="部门编号" prop="sn">
          <el-input v-model="editForm.sn" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="editForm.state">
            <el-radio class="radio" :label="1">启用</el-radio>
            <el-radio class="radio" :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="部门经理">
          <!--          <el-input v-model="editForm.manager" auto-complete="off"></el-input>-->
          <!--
          el-select - 下拉选择器
            el-option - 每个选项
              :key - 元素的唯一标识
              :label - 选择完以后选择框展示的信息
              :value - 要提交的后台的值
          -->
          <el-select v-model="editForm.manager" value-key="id" placeholder="请选择">
            <el-option
                v-for="employee in employees"
                :key="employee.id"
                :label="employee.username"
                :value="employee">
              <span style="float: left">{{ employee.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ employee.phone }}</span>
            </el-option>
          </el-select>
        </el-form-item>


        <el-form-item label="上级部门">
          <!--          <el-input v-model="editForm.parent" auto-complete="off"></el-input>-->
          <el-cascader v-model="editForm.parent"
                       :options="tree"
                       :props="{ checkStrictly: true,value:'id',label:'name'}"
                       clearable></el-cascader>

        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="editFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>

  </section>
</template>

<script>
import util from '../../common/js/util'
//import NProgress from 'nprogress'
import { getDepartmentListPage, removeDepartment, batchRemoveDepartment, editDepartment, addDepartment } from '../../api/api';

export default {
  data() {
    return {
      title:'',
      filters: {
        name: ''
      },
      departments: [],
      employees:[],
      tree:[],
      totals: 0,
      pageSize: 5,
      currentPage: 1,

      listLoading: false,
      sels: [],//列表选中列

      editFormVisible: false,//编辑界面是否显示
      editLoading: false,
      editFormRules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' }
        ],
        sn: [
          { required: true, message: '请输入部门编号', trigger: 'blur' }
        ]
      },
      //编辑或新增界面数据
      editForm: {
        id: null,
        name: '',
        sn: '',
        state: 1,
        manager: null,
        parent: null
      }
    }
  },
  methods: {
    search(){
      this.currentPage = 1;
      this.getDepartments();
    },
    //性别显示转换
    formatSex: function (row, column) {
      return row.state == 1 ? '<span style="color: green">启用</span>' : row.state == 0 ? '禁用' : '未知';
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getDepartments();
    },
    //获取部门列表
    getDepartments() {
      let para = {
        pageSize: this.pageSize,
        currentPage:this.currentPage,
        keyWord: this.filters.name
      };
      this.listLoading = true;/*开启页面加载忙等*/

      /*向后台发起请求*/
      this.$http.post("/dept",para)
          .then(res=>{
            this.listLoading = false;/*开启页面加载忙等*/
            console.log(res) /*res.data==PageList*/
            this.departments = res.data.data/*把当前页的数据给模型层*/
            this.total = res.data.totals
          })
          .catch(res=>{

          })
    },
    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {/*如果点击的是确认*/
        this.listLoading = true;/*页面加载忙等*/
        //NProgress.start();
        let para = { id: row.id };/*获取id*/

        /*发送删除请求*/
        this.$http.delete("/dept/" + row.id)
            .then(res=>{
              this.listLoading = false;/*关闭页面加载忙等*/
              if (res.data.success){
                this.$message({
                  message: '删除成功',
                  type: 'success'
                });
                /*根据公司需求 1.就在当前页 2.回到上一页 3.回到第一页*/
                this.currentPage = 1;/*回到第一页*/
                this.getDepartments();

              }else {
                this.$message({
                  message: '删除失败',
                  type: 'error'
                });
              }
            })/*请求发送成功*/

            .catch(res=>{
              this.$message({
                message: '请求发送失败',
                type: 'error'
              });
            })/*请求发送失败*/
      }).catch(() => {/*如果点击取消*/

      });
    },
    //显示编辑界面
    handleEdit: function (index, row) {
      this.getTree();
      this.title = "编辑";
      this.editFormVisible = true;
      this.editForm = Object.assign({}, row);
      console.log(this.editForm)

      let dirPath = this.editForm.dirPath;/* /1/56/79 [1,56]*/
      console.log(dirPath);
      let dirPath1 = dirPath.split("/")
      console.log(dirPath1);

      let dirPathPara = [];
      for (let i = 1;i<dirPath1.length - 1;i++){
        dirPathPara.push(parseInt(dirPath1[i]))
      }

      /*实现回显*/
     this.editForm.parent = dirPathPara
    },
    //显示新增界面
    handleAdd: function () {
      this.getTree();
      this.title = "新增";
      this.editFormVisible = true;
      this.editForm = {/*清空表单*/
        id: null,
        name: '',
        sn: '',
        state: 1,
        manager: null,
        parent: null
      };
    },
    //编辑
    editSubmit: function () {
      this.$refs.editForm.validate((valid) => {/*主动触发校验规则*/
        if (valid) {/*如果验证通过*/
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.editLoading = true;/*开启提交按钮忙等*/
            //NProgress.start();
            let para = Object.assign({}, this.editForm);/*表单拷贝给新的值*/

            let arr = para.parent
            if (arr) {
              let paramParentObj = {id: arr[arr.length - 1]}
              para.parent = paramParentObj;
            }
            console.log(131456)
            console.log(para)
            /*发起提交表单请求*/
            this.$http.put("/dept",para).then(res=>{
              this.editLoading = false;/*开启提交按钮忙等*/
              console.log(333333)
              console.log(res);
              if (res.data.success){/*后台返回操作成功*/
                this.editFormVisible = false;/*关闭对话框*/
                this.getDepartments();
              }else {
                this.$message.error(res.data.message)
              }
            }).catch(res=>{
              this.$message.error("请求发送失败")
            })

          });
        }
      });
    },
    selsChange: function (sels) {
      this.sels = sels;

    },
    //批量删除
    batchRemove: function () {
      var ids = this.sels.map(item => item.id);/*把行数组转换为id数组 [1,2,3]*/
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        //NProgress.start();
        this.$http.patch("/dept",ids)
            .then(res=>{
              this.listLoading = false;/*关闭页面加载忙等*/
              if (res.data.success){
                this.$message({
                  message: '删除成功',
                  type: 'success'
                });
                /*根据公司需求 1.就在当前页 2.回到上一页 3.回到第一页*/
                this.currentPage = 1;/*回到第一页*/
                this.getDepartments();/*刷新列表*/

              }else {
                this.$message({
                  message: '删除失败',
                  type: 'error'
                });
              }
            })/*请求发送成功*/

            .catch(res=>{
              this.$message({
                message: '请求发送失败',
                type: 'error'
              });
            })/*请求发送失败*/

      }).catch(() => {

      });
    },
    /*查询所有员工*/
    getEmployees:function (){
      this.$http.get("/employee").then(res=>{
        this.employees = res.data;
        console.log(res);
      }).catch(res=>{
        this.$message.error("获取员工请求发送失败")
      })
    },
    /*查询部门树状结构*/
    getTree:function (){
      this.$http.get("/dept/getTree").then(res=>{
        this.tree = res.data;
        console.log(res);
      }).catch(res=>{
        this.$message.error("获取树状部门请求发送失败")
      })
    }
  },
  mounted() {/*页面加载完成就执行*/
    this.getDepartments();/*调用获取数据的方法*/
    this.getEmployees();/*调用获取所有员工的方法*/
  }
}

</script>

<style scoped>

</style>